package com.xxd.spring.boot.demo.wubolin.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xxd.spring.boot.demo.wubolin.entity.User;
import com.xxd.spring.boot.demo.wubolin.util.DateUtil;
import com.xxd.spring.boot.demo.wubolin.util.UserManagerUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        boolean createTime = metaObject.hasSetter("creatTime");
        if(createTime){
            Object creatTimeValue = metaObject.getValue("creatTime");
            if(Objects.isNull(creatTimeValue)){
                metaObject.setValue("creatTime", DateUtil.dateFmt(new Date()));
            }
        }
        boolean creatBy = metaObject.hasSetter("creatBy");
        if(creatBy){
            Object creatByValue = metaObject.getValue("creatBy");
            if(Objects.isNull(creatByValue)){
                User user = UserManagerUtil.get();
                metaObject.setValue("creatBy",user.getUsername());
            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        boolean updateTime = metaObject.hasSetter("updateTime");
        if(updateTime){
                metaObject.setValue("updateTime",DateUtil.dateFmt(new Date()));
        }
        boolean creatBy = metaObject.hasSetter("updateBy");
        if(creatBy){
                User user = UserManagerUtil.get();
                metaObject.setValue("updateBy",user.getUsername());
        }
    }
}
